/**
 * 头脑风暴会话本地存储管理
 * 提供localStorage备份、恢复和清理功能
 */

const STORAGE_KEY = 'brainstorm_sessions_backup';
const MAX_BACKUP_SESSIONS = 10;

export interface SessionBackup {
  sessionId: string;
  data: any;
  timestamp: number;
}

/**
 * 保存会话到localStorage
 */
export function saveSessionToLocal(sessionId: string, sessionData: any): void {
  try {
    const backups = getLocalBackups();

    // 更新或添加当前会话
    const existingIndex = backups.findIndex((b) => b.sessionId === sessionId);
    const newBackup: SessionBackup = {
      sessionId,
      data: sessionData,
      timestamp: Date.now(),
    };

    if (existingIndex >= 0) {
      backups[existingIndex] = newBackup;
    } else {
      backups.unshift(newBackup);
    }

    // 保持最多MAX_BACKUP_SESSIONS个备份
    const trimmedBackups = backups.slice(0, MAX_BACKUP_SESSIONS);
    localStorage.setItem(STORAGE_KEY, JSON.stringify(trimmedBackups));

    console.log(`[LocalStorage] Session ${sessionId} saved`);
  } catch (error) {
    console.error('[LocalStorage] Failed to save session:', error);
  }
}

/**
 * 从localStorage恢复会话
 */
export function loadSessionFromLocal(sessionId: string): any | null {
  try {
    const backups = getLocalBackups();
    const backup = backups.find((b) => b.sessionId === sessionId);

    if (backup) {
      console.log(`[LocalStorage] Session ${sessionId} loaded`);
      return backup.data;
    }

    return null;
  } catch (error) {
    console.error('[LocalStorage] Failed to load session:', error);
    return null;
  }
}

/**
 * 获取所有本地备份
 */
export function getLocalBackups(): SessionBackup[] {
  try {
    const stored = localStorage.getItem(STORAGE_KEY);
    if (!stored) return [];

    const backups = JSON.parse(stored) as SessionBackup[];

    // 过滤掉超过7天的备份
    const sevenDaysAgo = Date.now() - 7 * 24 * 60 * 60 * 1000;
    return backups.filter((b) => b.timestamp > sevenDaysAgo);
  } catch (error) {
    console.error('[LocalStorage] Failed to get backups:', error);
    return [];
  }
}

/**
 * 删除本地备份
 */
export function removeSessionFromLocal(sessionId: string): void {
  try {
    const backups = getLocalBackups();
    const filtered = backups.filter((b) => b.sessionId !== sessionId);
    localStorage.setItem(STORAGE_KEY, JSON.stringify(filtered));

    console.log(`[LocalStorage] Session ${sessionId} removed`);
  } catch (error) {
    console.error('[LocalStorage] Failed to remove session:', error);
  }
}

/**
 * 清除所有本地备份
 */
export function clearLocalBackups(): void {
  try {
    localStorage.removeItem(STORAGE_KEY);
    console.log('[LocalStorage] All backups cleared');
  } catch (error) {
    console.error('[LocalStorage] Failed to clear backups:', error);
  }
}

/**
 * 获取最近编辑的会话
 */
export function getRecentSessions(limit: number = 5): SessionBackup[] {
  try {
    const backups = getLocalBackups();
    return backups
      .sort((a, b) => b.timestamp - a.timestamp)
      .slice(0, limit);
  } catch (error) {
    console.error('[LocalStorage] Failed to get recent sessions:', error);
    return [];
  }
}

/**
 * 检查存储空间
 */
export function checkStorageSpace(): { used: number; available: number } {
  try {
    const test = 'test';
    let used = 0;

    // 估算已使用空间
    for (const key in localStorage) {
      if (localStorage.hasOwnProperty(key)) {
        used += localStorage[key].length + key.length;
      }
    }

    // localStorage通常限制为5MB
    const total = 5 * 1024 * 1024;
    const available = total - used;

    return {
      used: Math.round(used / 1024), // KB
      available: Math.round(available / 1024), // KB
    };
  } catch (error) {
    console.error('[LocalStorage] Failed to check storage space:', error);
    return { used: 0, available: 0 };
  }
}
